//
//  YASelectPicController.swift
//  添加视图辅助开发
//
//  Created by 鱼龙之梦 on 15/9/10.
//  Copyright © 2015年 panyanzhi. All rights reserved.
//

import UIKit

private let YASelectPicCellID = "YASelectPicCellID"
//注意：设置最大选择图片的数量
private let YAMAXPiCount = 9
class YASelectPicController: UICollectionViewController,YASelectPicCellDelegate{
    ///  定义存储数据源的变量
    lazy var pictures = [UIImage]()
    ///  记录当前选中照片的索引
    private var currentIndex = 0
    ///布局
    init(){
        let layout = UICollectionViewFlowLayout()
        super.init(collectionViewLayout:layout)
        layout.itemSize = CGSize(width: 90, height: 90)
        layout.sectionInset = UIEdgeInsets(top: 10, left: 5, bottom: 10, right: 10)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        
        super.viewDidLoad()
        collectionView?.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        
        self.collectionView!.registerClass(YASelectPicCell.self, forCellWithReuseIdentifier: YASelectPicCellID)
        
    }
    
    // MARK: UICollectionViewDataSource
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return pictures.count + (pictures.count == YAMAXPiCount ? 0:1)
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(YASelectPicCellID, forIndexPath: indexPath) as! YASelectPicCell
        
        cell.picDelegate = self
        
        cell.image = indexPath.item < pictures.count ? pictures[indexPath.item]:nil
        
        return cell
    }
     //MARK:--- 实现选中照片后方法
    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //注意：判断是否允许访问相册
        printLog("访问相册\(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary))")
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){
            printLog("不允许访问相册")
            return
        }
        //注意：记录当前选中的照片
        currentIndex = indexPath.item
        let vc = UIImagePickerController()//注意：打开照片的界面
        vc.delegate = self
        presentViewController(vc, animated: true, completion: nil)
    }
     //MARK:--- 实现删除cell的代理协议
    private func deletePicWithCell(cell: YASelectPicCell) {
        if let indexPath = collectionView?.indexPathForCell(cell) where indexPath.item < pictures.count {
            pictures.removeAtIndex(indexPath.item)
            collectionView?.reloadData()
        }
    }
}
//MARK: 实现选中照片的协议方法
//注意：要遵守两个协议
extension YASelectPicController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        //注意：要限制图片的大小
        let scaleImage = image.scaleImageToWidth(300)
        if currentIndex < pictures.count {
           pictures[currentIndex] = scaleImage
        }
        else
        {
            pictures.append(scaleImage)
        }
        collectionView?.reloadData()
        //注意：自己关掉控制器
        dismissViewControllerAnimated(true, completion: nil)
    }
}
//MARK: 处理cell的代理协议
private protocol YASelectPicCellDelegate:NSObjectProtocol{
    //注意：要将当前cell传过来
    //MARK:--- 删除代理
    func deletePicWithCell(cell:YASelectPicCell)
}
//MARK: 照片选择的cell类

private class YASelectPicCell:UICollectionViewCell{
    //MARK:--- 定义代理
    weak var picDelegate:YASelectPicCellDelegate?
    //MARK:--- 定义接收Image的变量，一旦接收立刻去设置图片按钮的图片
    var image:UIImage?{
        didSet{
            if image != nil {
                picBtn.setImage(image, forState: .Normal)
            } else {
                // 显示默认的加号图片
                picBtn.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
            }
            
            // 如果没有图像，隐藏删除按钮
            delBtn.hidden = (image == nil)
        }
    }
    //MARK:--- 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK:--- 执行代理方法
    @objc private func clickRemove(){
        picDelegate?.deletePicWithCell(self)
    }
    private func setupUI(){
        contentView.addSubview(picBtn)
        contentView.addSubview(delBtn)
        
        //注意：布局
        
        picBtn.frame = bounds
        delBtn.translatesAutoresizingMaskIntoConstraints = false
        let viewDict = ["btn":delBtn]
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[btn]-0-|", options: [], metrics: nil, views: viewDict))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[btn]", options: [], metrics: nil, views: viewDict))
        picBtn.userInteractionEnabled = false //注意：为了使用代理
        delBtn.addTarget(self, action: "clickRemove", forControlEvents: .TouchUpInside)
        //注意：让图片正常填充
        picBtn.imageView!.contentMode = UIViewContentMode.ScaleAspectFill

    }
    //MARK:--- 懒加载控件
    private lazy var picBtn :UIButton = UIButton(imageName: "compose_pic_add")
    private lazy var delBtn :UIButton = UIButton(imageName: "compose_photo_close")
}